import { loginAPI, getUserInfoAPI, getUserDetailById } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'

export default {
  namespaced: true,
  state: {
    token: getToken() || '',
    userInfo: {}
  },
  mutations: {
    SETTOKEN(state, payload) {
      state.token = payload
      setToken(payload)
    },
    SET_USER_INFO(state, payload) {
      state.userInfo = payload
    },
    REMOVE_USER_INFO(state) {
      // 清除信息
      state.token = ''
      state.userInfo = {}
      // 清除token
      removeToken()
    }
  },
  actions: {
    async fetchLogin(store, data) {
      const res = await loginAPI(data)
      store.commit('SETTOKEN', res)
      return res
    },
    async fetchUserInfo(store) {
      const res = await getUserInfoAPI()
      const res2 = await getUserDetailById(res.userId)
      store.commit('SET_USER_INFO', { ...res, ...res2 })
    }
  }
}
